package com.hzsd.zengbanyi.biaodan_text.Actrivity;


import hzst.android.entity.VersionInfo;
import hzst.android.util.UpdateManager;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.URLEncoder;

import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.hzsd.zengbanyi.biaodan_text.BaseActivity;
import com.hzsd.zengbanyi.biaodan_text.R;
import com.hzsd.zengbanyi.biaodan_text.bean.Group;
import com.hzsd.zengbanyi.biaodan_text.bean.GroupDAO;
import com.hzsd.zengbanyi.biaodan_text.bean.UrlPath;
import com.hzsd.zengbanyi.biaodan_text.bean.User;
import com.hzsd.zengbanyi.biaodan_text.bean.UserDAO;
import com.hzsd.zengbanyi.biaodan_text.utils.CheckHttpUtil;
import com.hzsd.zengbanyi.biaodan_text.utils.Constant;
import com.hzsd.zengbanyi.biaodan_text.utils.DownLoadFiles;
import com.hzsd.zengbanyi.biaodan_text.utils.GetWebJsonData;
import com.hzsd.zengbanyi.biaodan_text.utils.MD5Utils;
import com.igexin.sdk.PushManager;


public class LoginActivity extends BaseActivity {
    private MD5Utils md5Utils;
    private GroupDAO groupDAO;
    private UserDAO userDAO;
    private String DownLoadUrl;
    private SharedPreferences sp;
    private String urlPath, path;
    private String uploadPath;
    private String currentPath;
    private String source;
    private String sourcePath;
    private String fileName;
    private ArrayList<Group> groupList;
    private ArrayList<User> userList;
    private Spinner spinnerDepart, spinnerUser;
    private Button btnLogin, btnUrl;
    private ProgressDialog selectorDialog;
    private EditText edtPassword;
    private String name, password, loginName, group, userId, EName;
    private VersionInfo versionInfo;
    public static String FileFolder = "hzzc";
    private final static String File_PATH = Environment.getExternalStorageDirectory() + File.separator + FileFolder + File.separator;
    private static final int HANDLER_VERSION_INFO = 4;
    private static final int HANDLER_NOBASEDATA_INFO = -1;//没有数据库文件
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {

        @SuppressWarnings("unchecked")
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case 1:
                    selectorDialog.cancel();
                    groupList = (ArrayList<Group>) msg.obj;
                    ArrayList<String> data = new ArrayList<String>();
                    for (int i = 0; i < groupList.size(); i++) {
                        String groupName = groupList.get(i).G_CName;
                        data.add(groupName);
                    }
                    ArrayAdapter<String> adapter = new ArrayAdapter<String>(LoginActivity.this,
                            android.R.layout.simple_list_item_1, data);
                    spinnerDepart.setAdapter(adapter);
                    spinnerDepart.setSelection(0, true);
                    break;

                case 2:
                    userList = (ArrayList<User>) msg.obj;
                    ArrayList<String> data1 = new ArrayList<String>();
                    for (int i = 0; i < userList.size(); i++) {
                        String userName = userList.get(i).U_CName;
                        data1.add(userName);
                    }
                    adapter = new ArrayAdapter<String>(LoginActivity.this,
                            android.R.layout.simple_list_item_1, data1);
                    spinnerUser.setAdapter(adapter);


                    break;
                case 3:
                    selectorDialog.cancel();
                    Toast.makeText(LoginActivity.this, "链接错误，请重新设置服务器", Toast.LENGTH_SHORT).show();
                    dialogToShow();
                    break;
                case HANDLER_VERSION_INFO:
                    UpdateManager updateManager = new UpdateManager(LoginActivity.this);
                    updateManager.update(Constant.LOCAL_PATH_APK, "hjjc.apk", versionInfo);
                    downLoadDB();

                    break;
                case HANDLER_NOBASEDATA_INFO:
                    selectorDialog.cancel();
                    showMemberToast(Toast.LENGTH_SHORT, "找不到数据库，请链接网络下载！");
                    break;
            }

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_login);
        PushManager.getInstance().initialize(this.getApplicationContext());
        CheckHttpUtil.checkhttp(LoginActivity.this);
        sp = getSharedPreferences("user", MODE_PRIVATE);
        initBaseData();
        initview();
        getVersionData();
    }

    private void dialogToShow() {
        LayoutInflater factory = LayoutInflater.from(LoginActivity.this);
        final View textEntryView = factory.inflate(R.layout.dialog_input, null);
        TextView tv = (TextView) textEntryView.findViewById(R.id.tv_upload);
        tv.setText("请输入图片上传服务器地址");

        final EditText etUpLoad = (EditText) textEntryView.findViewById(R.id.et_upload);
        final EditText etUrlPath = (EditText) textEntryView.findViewById(R.id.et_urlpath);
        etUpLoad.setText(UrlPath.UpLoadService);
        etUrlPath.setText(UrlPath.Service);
        new AlertDialog.Builder(LoginActivity.this).setTitle("请输入服务器地址，如" + urlPath).setView(textEntryView).setPositiveButton("确定",

                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        sp = getSharedPreferences("user", MODE_PRIVATE);
                        SharedPreferences.Editor edit = sp.edit();
                        edit.putString("urlPath", etUrlPath.getText().toString());
                        edit.putString("upLoadurlPath", etUpLoad.getText().toString());
                        edit.commit();
                        UrlPath.Service = etUrlPath.getText().toString();
                        UrlPath.UpLoadService = etUpLoad.getText().toString();
                        System.out.println("登录页面的图片IP：" + UrlPath.UpLoadService);
                        downLoadDB();
                        initview();
                        try {//下面三句控制弹框的关闭

                            Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");

                            field.setAccessible(true);

                            field.set(dialog, true);//true表示要关闭

                        } catch (Exception e) {

                            e.printStackTrace();

                        }
                    }
                }).setNegativeButton("初始化", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                etUpLoad.setText(UrlPath.Default_UpLoadService);
                etUrlPath.setText(UrlPath.Default_Service);
                try {//下面三句控制弹框的关闭

                    Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");

                    field.setAccessible(true);

                    field.set(dialog, false);//true表示要关闭

                } catch (Exception e) {

                    e.printStackTrace();

                }
            }
        }).setNeutralButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                try {//下面三句控制弹框的关闭

                    Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");

                    field.setAccessible(true);

                    field.set(dialog, true);//true表示要关闭

                } catch (Exception e) {

                    e.printStackTrace();

                }
            }
        })
                .setCancelable(false).show();

    }

    private void initDB() {
        UrlPath.Service = sp.getString("urlPath", "");
        UrlPath.UpLoadService = sp.getString("upLoadurlPath", "");
        File file = getDatabasePath("user.db");
        file.getParentFile().mkdirs();

        try {
            InputStream is = new FileInputStream(currentPath);
            FileOutputStream fos = new FileOutputStream(file);

            byte[] buf = new byte[10240];
            int readLen = -1;
            while ((readLen = is.read(buf)) != -1) {
                fos.write(buf, 0, readLen);
                fos.flush();
            }
            fos.close();
            is.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void initBaseData() {
        urlPath = sp.getString("urlPath", "");
        uploadPath = sp.getString("upLoadurlPath", "");
    }

    private void initview() {

        spinnerDepart = (Spinner) findViewById(R.id.tv_departname);
        spinnerUser = (Spinner) findViewById(R.id.tv_username);
        btnLogin = (Button) findViewById(R.id.btnlogin);
        btnUrl = (Button) findViewById(R.id.btn_url);
        edtPassword = (EditText) findViewById(R.id.tv_password);

        btnUrl.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                dialogToShow();

            }

        });

        btnLogin.setOnClickListener(new OnClickListener() {

            @SuppressLint("DefaultLocale")
            @SuppressWarnings("static-access")
            @Override
            public void onClick(View v) {
                password = edtPassword.getText().toString();
                String passmd5 = md5Utils.MD5(password).toUpperCase();
                String Upassword = userDAO.getPassword(name);
                if (password.equals("")) {
                    Toast.makeText(LoginActivity.this, "请输入密码", Toast.LENGTH_SHORT).show();
                } else {

                    if (passmd5.equals(Upassword)) {
                        SharedPreferences.Editor edit = sp.edit();
                        edit.putString("group", group);
                        edit.putString("name", name);
                        edit.putString("password", password);
                        edit.putString("userId", userId);
                        edit.putString("EName", EName);
                        edit.putString("loginName", loginName);
                        edit.commit();
                        Intent intent = new Intent(LoginActivity.this, MainActivity.class);

                        startActivity(intent);
                        finish();
                        Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(LoginActivity.this, "密码错误", Toast.LENGTH_SHORT).show();

                    }


                }
            }
        });
        spinnerUser.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int position, long id) {
                name = parent.getItemAtPosition(position).toString();
                userId = userList.get(position).UserID;
                EName = userList.get(position).U_EName;
                loginName = userList.get(position).getU_LoginName();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        spinnerDepart.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(final AdapterView<?> parent, View view,
                                       final int position, long id) {
                new Thread() {
                    public void run() {

                        String groupid = groupList.get(position).GroupID;
                        group = parent.getItemAtPosition(position).toString();
                        userList = userDAO.getUserName(groupid);
                        Message msg = Message.obtain();
                        msg.obj = userList;
                        msg.what = 2;
                        handler.sendMessage(msg);
                    }
                }.start();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }


    private void downLoadDB() {
        selectorDialog = ProgressDialog.show(this, null, "正在加载，请稍等...", true, false);
        selectorDialog.setCancelable(true);
        selectorDialog.setCanceledOnTouchOutside(false);

        SDcardIsExist();
        new Thread() {
            public void run() {
                try {
                    if (wifiState(LoginActivity.this) == true) {
                        DownLoadUrl = DownLoadFiles.readParse("http://" + urlPath + UrlPath.USER_PATH);
                        source = "http://" + urlPath + DownLoadUrl;
                        sourcePath = source.substring(0, source.lastIndexOf("/")) + "/";
                        fileName = source.substring(source.lastIndexOf("/") + 1, source.lastIndexOf("."));
                        currentPath = File_PATH + fileName + ".db";
                        String encodeStr = URLEncoder.encode(fileName + ".rar", "UTF-8");
                        path = sourcePath + encodeStr;
                        DownLoadFiles.download(path, currentPath);
                        initDB();
                        groupDAO = new GroupDAO(LoginActivity.this);
                        userDAO = new UserDAO(LoginActivity.this);
                        groupList = groupDAO.getGroupName();
                        Message msg = Message.obtain();
                        msg.obj = groupList;
                        msg.what = 1;
                        handler.sendMessage(msg);
                    } else {//没网，先判断本地是否有数据库
                        File file = new File("data/data/" + getPackageName() + "/databases/user.db");
                        if (file.exists()) {//本地有数据库
                            groupDAO = new GroupDAO(LoginActivity.this);
                            userDAO = new UserDAO(LoginActivity.this);
                            groupList = groupDAO.getGroupName();
                            Message msg = Message.obtain();
                            msg.obj = groupList;
                            msg.what = 1;
                            handler.sendMessage(msg);
                        } else {//本地没有数据库
                            Message msg = Message.obtain();
                            msg.what = -1;
                            handler.sendMessage(msg);
                        }
                    }
                } catch (Exception e) {
                    Log.i("zby", e.toString());
                    e.printStackTrace();
                    Message msg = Message.obtain();
                    msg.what = 3;
                    handler.sendMessage(msg);
                }
            }
        }.start();

    }

    /***
     * app更新
     */
    private void getVersionData() {

        //final String updateurl="http://"+uploadPath+"/SystemInfo.ashx?method=version";
        final String updateurl = "http://" + uploadPath + "/AppModules/PadInterface/SystemInfo.ashx";
        new Thread() {
            public void run() {
                try {
                    versionInfo = GetWebJsonData.getVersionInfo(updateurl, uploadPath);
                    Message msg = Message.obtain();
                    msg.what = HANDLER_VERSION_INFO;
                    handler.sendMessage(msg);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();

    }

    private void SDcardIsExist() {
        boolean sdCardExist = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
        if (!sdCardExist) {
            Toast.makeText(LoginActivity.this, "请插入SD卡", Toast.LENGTH_SHORT).show();
        } else {
            File dirFirstFile = new File(File_PATH);
            if (!dirFirstFile.exists()) {
                dirFirstFile.mkdir();

            }
        }
    }

}
